package com.googlecode.lookie.platform;

import java.util.ArrayList;
import java.util.List;

import org.springframework.richclient.application.support.DefaultApplicationServices;

import com.googlecode.lookie.platform.service.PlatformServiceDescriptor;

public class PlatformApplicationServices
    extends DefaultApplicationServices
{

    private List<PlatformServiceDescriptor> getDescriptors()
    {
        Object osgiBeans = getApplicationContext().getBean( "platformServiceDescriptors" );
        List<PlatformServiceDescriptor> list = new ArrayList<PlatformServiceDescriptor>();
        for ( Object bean : ( (List<?>) osgiBeans ) )
        {
            PlatformServiceDescriptor descriptor = (PlatformServiceDescriptor) bean;
            list.add( descriptor );
        }
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected boolean containsServiceForClassType( Class serviceType )
    {
        boolean contains = super.containsServiceForClassType( serviceType );
        if ( !contains )
        {
            for ( PlatformServiceDescriptor descriptor : getDescriptors() )
            {
                if ( descriptor.getServiceType().equals( serviceType ) )
                {
                    contains = true;
                    break;
                }
            }
        }
        return contains;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Object getServiceForClassType( Class serviceType )
    {
        Object service = super.getServiceForClassType( serviceType );
        if ( service == null )
        {
            for ( PlatformServiceDescriptor descriptor : getDescriptors() )
            {
                if ( descriptor.getServiceType().equals( serviceType ) )
                {
                    service = descriptor.getService();
                    break;
                }
            }
        }
        return service;
    }

}
